<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('admin_logs', function (Blueprint $table) {
            $table->id();
            $table->foreignId('user_id')->nullable()->constrained()->onDelete('set null');
            $table->string('user_name')->nullable(); // 保存用户名，即使用户被删除
            $table->string('action'); // create, update, delete, view, login, logout
            $table->string('module'); // products, orders, users, categories, etc.
            $table->string('model_type')->nullable(); // 模型类型
            $table->unsignedBigInteger('model_id')->nullable(); // 模型ID
            $table->text('description'); // 操作描述 - 使用 text 类型以支持长文本
            $table->json('old_data')->nullable(); // 修改前的数据
            $table->json('new_data')->nullable(); // 修改后的数据
            $table->string('ip_address', 45)->nullable();
            $table->text('user_agent')->nullable(); // user_agent 也可能很长
            $table->text('url')->nullable(); // URL 也可能很长
            $table->string('method', 10)->nullable(); // GET, POST, PUT, DELETE
            $table->timestamps();
            
            // 索引
            $table->index('user_id');
            $table->index('action');
            $table->index('module');
            $table->index(['model_type', 'model_id']);
            $table->index('created_at');
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('admin_logs');
    }
};
